package com.emm.yixun.mobile.ui.customer;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.CustomerAdapter;
import com.emm.yixun.mobile.adapter.NotSignedAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetCustomerList;
import com.emm.yixun.mobile.ui.FirstContactActivity;
import com.emm.yixun.mobile.ui.web.WebActivity;
import com.emm.yixun.utils.ToastUtils;
import com.eroad.product.tools.PickerView;
import com.eroad.product.tools.PickerView.onSelectListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.vgo.app.swipemenulistview.SwipeMenu;
import com.vgo.app.swipemenulistview.SwipeMenuCreator;
import com.vgo.app.swipemenulistview.SwipeMenuItem;
import com.vgo.app.swipemenulistview.SwipeMenuListView;
import com.vgo.app.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

/**
 * 
 * <p>
 * <b>Title：</b>搜索界面
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午4:04:49
 */
public class SearchCustomerActivity extends SwipeBackActivity {

	private static final String TAG = "SearchCustomerActivity";

	/** 1 客户过来的搜索 2 逾期未签约等过来的搜索 */
	private String TYPE = "1";

	/** 1未签约 2未付款 3待处理<类型：1、待处理客户；2、逾期未签约；3、逾期未付款> */
	private String TYPED = "";

	/** 标题 */
	private TextView title_main;

	/** 返回按钮 */
	private ImageView back_btn, ivBack;

	/** 输入框 */
	private EditText search_edittext;

	/** 搜索按钮 */
	private TextView search_btn;


	/** 提醒 */
	TextView tsons;

	/** 刷新侧滑菜单listview */
	SwipeMenuListView swip_list;

	/** 客户适配器 */
	CustomerAdapter ctadapter;

	/** 预期未签约付款等适配器 */
	NotSignedAdapter ntadapter;

	/** 指派 */
	View viewzp;

	/** 指派 */
	PopupWindow popuzp;

	/** 指派选择框选中的置业顾问 */
	private String selectName;

	private String SearchContent = "";

	/** 指派选择框选中的置业顾问 的下标 */
	private int SelectID;
	
	/** 侧滑关闭框架 */
	private SwipeBackLayout mSwipeBackLayout;

	@Override
	protected void onResume() {
		BaseActivity.activity = this; // TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_customer_activity);
		
		SetSwipeBackLayout(mSwipeBackLayout);
		
		BaseActivity.activity = this;
		TYPE = getIntent().getStringExtra("TYPE");
		TYPED = getIntent().getStringExtra("TYPED");
		Log.w("跳转过来的方式", "1 客户过来的搜索 2 逾期未签约过来的搜索 =====" + TYPE);
		initView();
		
		SetRelativiLayoutPadding(R.id.main_head_top_rela);
		
		initBtn();
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化view
	 * </p>
	 * <p>
	 * <b>Description：</b> 初始化view，以及初始化侧滑菜单样式
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:04:24
	 */
	private void initView() {
		back_btn = (ImageView) findViewById(R.id.back_btn);
		back_btn.setVisibility(View.VISIBLE);
		ivBack = (ImageView) findViewById(R.id.iv_back);
		search_edittext = (EditText) findViewById(R.id.search_edittext);
		search_btn = (TextView) findViewById(R.id.search_btn);
		tsons = (TextView) findViewById(R.id.tsons);
		swip_list = (SwipeMenuListView) findViewById(R.id.listView_search);

		// 判断类型选择加载侧滑菜单样式
		if (TYPE.equals("1") && "1".equals(EmmApplication.getData(EmmApplication.isDistributionCustomer))) {
			initMenuListView(1);
		} else {
			initMenuListView(2);
			// initMenuListView2();
		}

	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 打开list
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:04:52
	 */
	private void openList() {
		if (TYPE.equals("1")) {
			swip_list.setDividerHeight(1);
			ctadapter = new CustomerAdapter(SearchCustomerActivity.this, getcustomer.getCustomerList());
			swip_list.setAdapter(ctadapter);
		} else {
			swip_list.setDividerHeight(0);
			ntadapter = new NotSignedAdapter(SearchCustomerActivity.this, getcustomer.getCustomerList());
			swip_list.setAdapter(ntadapter);
		}
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化监听事件
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:05:31
	 */
	private void initBtn() {
		ivBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		back_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		search_edittext.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.length() > 0) {
					swip_list.setVisibility(View.VISIBLE);
					SearchContent = s.toString().trim();
					getSearchList(SearchContent);
				} else {
					dismissList();
				}
			}
		});
		search_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 搜索
				if (TextUtils.isEmpty(search_edittext.getText().toString().trim())) {
					// 输入框为空
					EmmApplication.T("请输入搜索内容");
				} else {
					diskey();
					// 隐藏搜索内容
					// 执行搜索操作
					getSearchList(search_edittext.getText().toString().trim());
				}
			}
		});

		swip_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if ("1".equals(getcustomer.getCustomerList().get(position).getDataAuthority())) {
					if (EmmApplication.IsLoadingCustomer) {
						Log.v(TAG, "正在跳转客户详情，该次操作无效");
						return;
					}
					final String customerId =  getcustomer.getCustomerList().get(position).getCustomerId();
					WebActivity.Companion.jump2CustomerDetail(activity, customerId);
				} else {
					ToastUtils.INSTANCE.showToast("无权限查看当前客户详情");
				}
			}
		});
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 客户搜索 配置listview的item侧滑菜单
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param type
	 *            1有权限 2无权限
	 * @author tangxin
	 * @date 2016年12月7日 上午11:05:50
	 */
	private void initMenuListView(final int type) {
		SwipeMenuCreator creator = new SwipeMenuCreator() {
			@Override
			public void create(SwipeMenu menu) {

				SwipeMenuItem openItem = new SwipeMenuItem(SearchCustomerActivity.this);
				// set item background
				openItem.setBackground(new ColorDrawable(Color.parseColor("#F82B49")));
				// set item width
				openItem.setWidth(dp2px(70));
				// set item title
				openItem.setTitle("打电话");
				// set item title fontsize
				openItem.setTitleSize(16);
				// set item title font color
				openItem.setTitleColor(Color.WHITE);
				// add to menu
				menu.addMenuItem(openItem);

				SwipeMenuItem openItem2 = new SwipeMenuItem(SearchCustomerActivity.this);
				openItem2.setBackground(new ColorDrawable(Color.parseColor("#FF6253")));
				openItem2.setWidth(dp2px(70));
				openItem2.setTitle("首触");
				openItem2.setTitleSize(16);
				openItem2.setTitleColor(Color.WHITE);
				menu.addMenuItem(openItem2);

				SwipeMenuItem openItem3 = new SwipeMenuItem(SearchCustomerActivity.this);
				openItem3.setBackground(new ColorDrawable(Color.parseColor("#FF7200")));
				openItem3.setWidth(dp2px(70));
				openItem3.setTitle("写跟进");
				openItem3.setTitleSize(16);
				openItem3.setTitleColor(Color.WHITE);
				menu.addMenuItem(openItem3);
				if (type == 1) {
					SwipeMenuItem openItem4 = new SwipeMenuItem(SearchCustomerActivity.this);
					openItem4.setBackground(new ColorDrawable(Color.parseColor("#ffb527")));
					openItem4.setWidth(dp2px(70));
					openItem4.setTitle("分配");
					openItem4.setTitleSize(16);
					openItem4.setTitleColor(Color.WHITE);
					menu.addMenuItem(openItem4);
				}
			}
		};
		swip_list.setMenuCreator(creator);
		// 侧滑菜单的相应事件
		swip_list.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
				boolean hasPermission = "1".equals(getcustomer.getCustomerList().get(position).getDataAuthority());
				if (hasPermission) {
					switch (index) {
						case 0:// 第一个添加的菜单的响应事件
							Log.w("侧滑菜单的相应事件1", "被点击");
							EmmApplication.callPhone(getcustomer.getCustomerList().get(position).getMobile(),
									getcustomer.getCustomerList().get(position).getCustomerId());
							break;
						case 1:// 第二个添加的菜单的响应事件
							Log.w("侧滑菜单的相应事件2", "被点击");
							Intent second = new Intent(SearchCustomerActivity.this, FirstContactActivity.class);
							second.putExtra(FirstContactActivity.CUSTOMER, getcustomer.getCustomerList().get(position));
							startActivity(second);
							break;
						case 2:// 第三个添加的菜单的响应事件
							Log.w("侧滑菜单的相应事件3", "被点击" + position);
							// EmmApplication.T("触发第三个按钮，写跟进");
							Intent intent = new Intent(SearchCustomerActivity.this, FollowUpActivity.class);
							intent.putExtra("customerId", getcustomer.getCustomerList().get(position).getCustomerId());
							startActivity(intent);
							break;
						case 3:// 第三个添加的菜单的响应事件
							Log.w("侧滑菜单的相应事件4", "被点击");
							List<String> listname = new ArrayList<String>();
							for (int u = 0; u < 10; u++) {
								listname.add("Name:" + u);
							}
							SetzpPopu(listname);
							break;
						default:
							break;
					}
				} else {
					ToastUtils.INSTANCE.showToast("您没有操作权限");
				}
				return true;
			}
		});
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 指派
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param listname
	 * @author tangxin
	 * @date 2016年12月7日 上午11:06:16
	 */
	public void SetzpPopu(final List<String> listname) {
		viewzp = LayoutInflater.from(SearchCustomerActivity.this).inflate(R.layout.popu_zp, null);
		popuzp = new PopupWindow(viewzp, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
				android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
		popuzp.setFocusable(true);
//		EmmApplication.setNumberLog(SearchCustomerActivity.this, 0.5f);// 改变popupwindow范围外的屏幕亮度
		popuzp.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
		popuzp.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		popuzp.showAtLocation(viewzp, Gravity.BOTTOM, 0, 0);
		popuzp.showAsDropDown(viewzp, 0, 0);
		popuzp.setFocusable(true);
		popuzp.setOutsideTouchable(true);
		viewzp.setFocusable(true);
		viewzp.setFocusableInTouchMode(true);
		viewzp.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					popuzp.dismiss();
					EmmApplication.setLog(SearchCustomerActivity.this);
				}
				return false;
			}
		});
		viewzp.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popuzp.dismiss();
				EmmApplication.setLog(SearchCustomerActivity.this);
			}
		});

		PickerView select_pick = (PickerView) viewzp.findViewById(R.id.select_pick);

		selectName = listname.get(0);

		TextView shuerbtn = (TextView) viewzp.findViewById(R.id.shuerbtn);

		ImageView dis_btn = (ImageView) viewzp.findViewById(R.id.dis_btn);
		dis_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popuzp.dismiss();
				EmmApplication.setLog(SearchCustomerActivity.this);
			}
		});

		RelativeLayout relative_all = (RelativeLayout) viewzp.findViewById(R.id.relative_all);
		select_pick.setData(listname);
		select_pick.setOnSelectListener(new onSelectListener() {
			@Override
			public void onSelect(String text, int id) {
				selectName = text;
				SelectID = id;
			}
		});
		select_pick.setSelected(0);
		shuerbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 确定
				popuzp.dismiss();
				EmmApplication.setLog(SearchCustomerActivity.this);
				EmmApplication.T("指派完成,指派给:" + selectName + "==>ID:" + SelectID);
			}
		});
		relative_all.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});

	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 去重
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param list
	 *            入参list
	 * @return
	 * @author tangxin
	 * @date 2016年12月7日 上午11:06:32
	 */
	public static List<String> removeDuplicate(List<String> list) {
		Set set = new LinkedHashSet<String>();
		set.addAll(list);
		list.clear();
		list.addAll(set);
		return list;
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 关闭键盘
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:07:21
	 */
	public void diskey() {
		try {
			((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(SearchCustomerActivity.this
					.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (NullPointerException e) {
		}
	}

	// 将dp转化为px
	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
	}

	/** 客户列表 */
	GetCustomerList getcustomer;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 搜索列表
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param searchContent
	 * @author tangxin
	 * @date 2016年12月7日 上午11:07:44
	 */
	private void getSearchList(String searchContent) {
		EmmApplication.updateUrl("getSearchList");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("searchContent", searchContent);
		if ("2".equals(TYPE)) {
			map.put("cusType", TYPED);
		}
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("getSearchList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					dismissList();
					return;
				}
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					dismissList();
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getcustomer = JSONObject.parseObject(resData.toString(), GetCustomerList.class);
				if ("1".equals(getcustomer.getResult())) {
					Log.v("获取成功", "");
					if (getcustomer.getCustomerList() != null) {
						openList();
					} else {
						EmmApplication.Ts("没有搜索到客户");
						dismissList();
					}
				} else {
					// EmmApplication.T("加载失败,请稍后再试");
					EmmApplication.Ts(getcustomer.getErrorMsg().toString());
					dismissList();
					Log.v("获取失败", "errorCode:" + getcustomer.getErrorCode().toString() + "errorMsg:" + getcustomer.getErrorMsg().toString());
				}
			}
		});
	}

	private void dismissList() {
		swip_list.setVisibility(View.GONE);
	}

}